package chances.epg.session;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import chances.epg.commons.log.EpgLogFactory;

@Service
public class UserSessionService {

	private Map<String, UserSession> userSessions = new HashMap<String, UserSession>();

	@Value("${epg.session.timeout:180}")
	private int timeout;

	@Value("${epg.session.enableTimeout:false}")
	private boolean enableTimeout;

	public void add(UserSession userSession) {
		if (this.userSessions.containsKey(userSession.getUserId())) {
			EpgLogFactory.getSystemLogger().debug("replace UserSessioin {}", userSession.getUserId());
		}
		this.userSessions.put(userSession.getUserId(), userSession);
		EpgLogFactory.getLogonlogger().info("{},{},{},{},{}", userSession.getUserId(), userSession.getSessionId(),
				userSession.getCreateTime(), userSession.getLastActiveTime(), userSession.getActiveTime(),userSession.returnUrl);
	}

	public boolean remove(String stbNo) {
		if (userSessions.containsKey(stbNo)) {
			UserSession userSession = this.userSessions.get(stbNo);
			EpgLogFactory.getLogoutlogger().info("{},{},{},{},{}", userSession.getUserId(), userSession.getSessionId(),
					userSession.getCreateTime(), userSession.getLastActiveTime(), userSession.getActiveTime());
			userSessions.remove(stbNo);
			return true;
		} else {
			return false;
		}
	}

	



	public boolean exist(String stbNo) {
		return userSessions.containsKey(stbNo);
	}

	public UserSession get(String stbNo) {
		if (StringUtils.isEmpty(stbNo)) {
			return null;
		} else {
			return userSessions.get(stbNo);
		}
	}

	public Stream<UserSession> stream() {
		return userSessions.values().stream();
	}

	public Map<String, UserSession> getUserSessions() {
		return userSessions;
	}

	public int getTimeout() {
		return timeout;
	}

	public boolean isEnableTimeout() {
		return enableTimeout;
	}

	public void setUserSessions(Map<String, UserSession> userSessions) {
		this.userSessions = userSessions;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public void setEnableTimeout(boolean enableTimeout) {
		this.enableTimeout = enableTimeout;
	}

	@Scheduled(fixedDelay = 60000)
	public void clearTimeout() {
		if (!this.enableTimeout)
			return;
		List<UserSession> timeOuts = new ArrayList<UserSession>();
		this.userSessions.values().forEach(s -> {
			int timeoutMill = this.timeout * 60000;
			if (s.isTimeout(timeoutMill)) {
				timeOuts.add(s);
			}
		});
		timeOuts.forEach(s -> {
			this.remove(s.getUserId());
		});
	}
}
